package com.xxxy.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

/**
 * 从Spring容器中取Bean
 */
@Component
public class BeanUtils implements ApplicationContextAware {
    //将管理上下文的applicationContext设置成静态变量，供全局调用
    public static ConfigurableApplicationContext applicationContext;

    //定义一个获取已经实例化bean的方法
    public static <T> T getBean(Class<T> c) {
        return applicationContext.getBean(c);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        BeanUtils.applicationContext = (ConfigurableApplicationContext) applicationContext;
    }
}
